package org.hxd.document.controller;

import org.apache.commons.io.FileUtils;
import org.hxd.document.service.DocumentService;
import org.hxd.pojo.Document;
import org.hxd.pojo.User_inf;
import org.hxd.units.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("/document")
public class DocumentController {
    @Autowired
    DocumentService documentService;

    //查询所有Document，或者根据条件查询
    @RequestMapping("/findDocument")
    public String findDocument(Document document, @RequestParam(defaultValue = "1") int pageIndex, Model model) {
        PageModel pageModel = new PageModel();
        pageModel.setPageIndex(pageIndex);
        //pageModel.setTotalSize(9);
        int rocordCount = documentService.findDocumentcount(document);
        pageModel.setRocordCount(rocordCount);
        List<Document> documents = documentService.findDocument(document, pageModel);
        model.addAttribute("documents", documents);
        model.addAttribute("pageModel", pageModel);
        model.addAttribute("title", document.getTitle());
        return "jsp/document/document";
    }

    //根据id 查找Document，进入修改页面
    @RequestMapping("/findDocumentByid")
    public String findDocumentByid(Integer id, Model model, String title, int pageIndex) {
        Document document = documentService.findDocumentByid(id);
        model.addAttribute("document", document);
        model.addAttribute("msg", title);
        model.addAttribute("pageIndex", pageIndex);
        return "jsp/document/showUpdateDocument";
    }

    //删除文档
    @RequestMapping("/removeDocument")
    @ResponseBody
    public String removeDocument(Integer[] ids, HttpServletRequest request) throws UnsupportedEncodingException {
        int rows = 0;
        for (Integer id : ids) {
            String path = request.getSession().getServletContext().getRealPath("/upload/");
            Document document = documentService.findDocumentByid(id);
            String filename = document.getFilename();
            //删除本地磁盘文件
            File file = new File(path,filename);
            if(file.exists()){
                file.delete();
            }
            int i = documentService.removeDocument(id);
            rows += i;
        }
        if (rows == ids.length) {
            return "OK";
        } else {
            return "FAIL";
        }
    }


    //修改文档
    @RequestMapping("/updateDocument")
    public String updateDocument(Document document, Model model, HttpSession session,int pageIndex,String msg) throws IOException {
        if (!document.getMultipartFile().isEmpty()) {//文件不能为空
            String path = session.getServletContext().getRealPath("/upload/");
            Document document1 = documentService.findDocumentByid(document.getId());
            File file = new File(path, document1.getFilename());
            if (file.exists()) {
                file.delete();//删除原来的文件
            }
            String filename = document.getMultipartFile().getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid+"_"+filename;
            document.getMultipartFile().transferTo(new File(path + File.separator + filename));
            document.setFilename(filename);
        }
        User_inf user = (User_inf) session.getAttribute("user");
        document.setUser_inf(user);
        int rows = documentService.modifyDocument(document);
        if (rows > 0) {
            return "redirect:/document/findDocument?pageIndex="+pageIndex+"&title="+msg;
        } else {
            model.addAttribute("fail", "文件修改失败！");
            return "jsp/fail";
        }
    }

    //上传文档
    @RequestMapping("/addDocument")
    public String addDocument(Document document, Model model, HttpSession session) throws IOException {
        // 1. 指定文件上传保存的位置
        String path = session.getServletContext().getRealPath("/upload/");
        // 判断该路径是否存在
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()){
            file.mkdirs();
        }
        // 2. 获取上传文件的名称
        String filename = document.getMultipartFile().getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+"_"+filename;
        // 3.上传文件
        document.getMultipartFile().transferTo(new File(path + File.separator + filename));//File.separator相当于'\'
        document.setFilename(filename);
        User_inf user = (User_inf) session.getAttribute("user");
        document.setUser_inf(user);
        //执行插入操作
        int rows = documentService.addDocument(document);
        if (rows > 0) {
            PageModel pageModel = new PageModel();
            int documentcount = documentService.findDocumentcount(null);
            pageModel.setRocordCount(documentcount);
            return "redirect:/document/findDocument?pageIndex=" + pageModel.getTotalSize();
        } else {
            model.addAttribute("fail", "文件上传失败！");
            return "jsp/fail";
        }
    }

    //下载文档
    @RequestMapping("/downLoad")
    public ResponseEntity<Object> downLoad(Integer id, HttpServletRequest request) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/upload/");
        Document document = documentService.findDocumentByid(id);
        String filename = document.getFilename();
        File file = new File(path+File.separator+filename);
        if(file.exists()){
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment",new  String(document.getFilename().getBytes( "utf-8" ),  "ISO8859-1" ));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<Object>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }else {
            String error = "下载的文档不存在！";
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
            headers.setContentType(mediaType);
            return new ResponseEntity<Object>(error,headers, HttpStatus.OK);
        }
    }
}
